<template>
	<view class="discover">
		<view class="content">
			<view class="con-top">
				<view class="site">
					<image src="/static/icon/site2.png" class="icon"></image>
					<view class="note">{{site}}</view>
					<image src="/static/icon/arrow2.png" class="arrow"></image>
				</view>
				<view class="search-nav"> 
					<input type="text" class="search" placeholder="想租哪里的房" @click="search">
					<image src="/static/icon/search.png" class="search-icon"></image>
				</view>
				
				<view class="hot">
					<image class="icon" src="/static/icon/hot.png"></image>
					<view class="note">热搜:</view>
					<ul class="keywords">
						
						<li v-for="(item,index) in hotwordsList"><navigator :url="'/pages/discover/all?keywords='+item.name">{{item.name}}</navigator></li>
						
						
						
						
					</ul>
				</view>         
				<swiper class="swiper" :indicator-dots="indicatorDots" :autoplay="autoplay" :interval="interval" :duration="duration">
						
					<swiper-item v-for="(item, index) in banner">
						<view class="swiper-item"><image :src="item.image"></image></view>
					</swiper-item>
					
				</swiper>
				
				<navigator url="../discover/all">
				<view class="find-nav">
					<image src="/static/img/all.png"></image>
					<view class="note">全部</view>							
				</view>
				</navigator>
				<navigator url="../discover/map">						
				<view class="find-nav" style="margin-left:88rpx;">
					<image src="/static/img/map.png"></image>
					<view class="note">地图找房</view>							
				</view>						
				</navigator>
				<view class="find-nav" style="margin-left:88rpx;">
					<image src="/static/img/cheap.png"></image>
					<view class="note">优惠好房</view>							
				</view>
				
				<view class="find-nav" style="margin-left:88rpx;">
					<image src="/static/img/short.png"></image>
					<view class="note">短租</view>							
				</view>	
				
				
				
				<view class="rec">
					<view class="one comm">为你推荐</view>
					<view class="two comm" :class="tabIndex_all==1 ? 'border-bottom' : ''">
						<view class="note"   @click="all">全部</view>
						
					</view>
					
					<view class="three comm" :class="tabIndex_near==1 ? 'border-bottom' : ''">
						<view class="note"   @click="getLocation">附近</view>
						
					</view>
				</view>								
			</view>
			
		</view>	
		<view class="con-bottom">	
			<view class="house">
				
				<navigator :url="'../discover/houseDetail?house_id='+item.id" v-for="(item,index) in houseall">
				<view class="house-list" >
					<image v-if="item.image" :src="siteUrl+item.image"></image>
					<image v-else :src="siteUrl+item.images.split(',',1)"></image>
					
					
					<view class="title">{{item.title}}</view>
					<view class="site">
						<image src="/static/icon/site2.png"></image>
						<view class="note">{{item.location_near}}</view>
					</view>
					<view class="price">{{item.price}} <font style="color:#373737;">元/月</font></view>
				</view>
				</navigator>
				
				<uni-load-more  :loadingType="loadingType" :contentText="contentText" :status="status" style="float:left;padding-left:30%"></uni-load-more>
			</view>
			
			
			
		</view>
			
				
		
								
		
		
		
		<uni-popup :show="type === 'showpopup'" mode="fixed" @hidePopup="togglePopup('')">
		    <view class="popup-view">
		        <text class="popup-title">需要用户授权位置权限</text>
		        <view class="uni-flex popup-buttons">
		            <button class="uni-flex-item" type="primary" open-type="openSetting" @tap="openSetting">设置</button>
		            <button class="uni-flex-item" @tap="togglePopup('')">取消</button>
		        </view>
		    </view>
		</uni-popup>	
		
		
	</view>
</template>

<script>
	var _self,
	page = 1,
	timer = null;
	import uniLoadMore from '@/components/uni-load-more/uni-load-more.vue'
	import uniPopup from '@/components/uni-popup/uni-popup.vue'
	var util = require('../../common/util.js');
	var formatLocation = util.formatLocation;
	// #ifdef APP-PLUS
	import permision from "@/common/permission.js"
	// #endif
	export default {
		components: {
		   uniPopup,uniLoadMore
		},
		data() {
			return {
				siteUrl:this.websiteUrl,
				//all:true,
				//near:false,
				xian_all:true,
				xian_location:false,
				banner: [],				
				houseall : [],
				hotwordsList:{},
				status: 'more',
				loadingText: '加载中...',
				loadingType: 2,//定义加载方式 0---contentdown  1---contentrefresh 2---contentnomore
				contentText: {
					contentdown:'上拉显示更多',
					contentrefresh: '正在加载...',
					contentnomore: '没有更多数据了'
				},
				addressList:{},
				site:'',
				indicatorDots: true,
				autoplay: true,
				interval: 2000,
				duration: 500,
				location: {},
				lon:0,
				lat:0,
				action:'all',
				type: '',
				hasLocation: false,
				title: 'getLocation',
				
				tabIndex_all:0,
				tabIndex_near:0,
				stateTab:true
			}
		},
			
		onLoad() {
			_self = this;
			_self.dp = 'block'		
		    this.getbanner();
			this.gethouseall();	
			this.gethotwordsList();
			this.stateTab = false			
			uni.getLocation({
			            type: 'wgs84',
			            success: function(res) {			    
							console.log(res)
							
			                var point = new plus.maps.Point(res.longitude, res.latitude);				
			                plus.maps.Map.reverseGeocode(
			                    point,
			                    {},
			                    function(event) {
									console.log(event)								
			                        var address = event.address; // 转换后的地理位置
			                        var point = event.coord; // 转换后的坐标信息
			                        var coordType = event.coordType; // 转换后的坐标系类型			                        
			                        var reg = /.+?(省|市|自治区|自治州|县|区)/g;			                        			                     
			                        _self.addressList=address.match(reg).toString().split(",");
									console.log(_self.addressList)
			                        _self.site= _self.addressList[2];
									console.log(_self.site)							  																	  
			                    },
			                    function(e) {}
			                );
			            }
			});	
						
						
						
		},
		onShow() {
			if(this.stateTab){
				this.gethotwordsList()
			}
			this.stateTab = true
		},
		onPullDownRefresh: function() {
			//下拉刷新的时候请求一次数据
			
		    this.gethouseall()					
		},
		onReachBottom: function() {
			//触底的时候请求数据，即为上拉加载更多
			//为了更加清楚的看到效果，添加了定时器
		    if (timer != null) {
		        clearTimeout(timer);
		    }		   
			 _self.getmorenews();
		},
		methods: {
												
			gethotwordsList(){
				uni.request({
					url: this.websiteUrl+'/userapi.php/Trends/hotkeywords',
					method: 'GET',
					header: {
						'content-type':'application/x-www-form-urlencoded'				
					},
					data: {},
					success: res => {
						//console.log(res)
						if(res.data.code ==1){
							 
							 _self.hotwordsList = res.data.data
						}
					},
					fail: () => {},
					complete: () => {}
				});
			},
			togglePopup(type) {
			        this.type = type;
			    },
			    showConfirm() {
			        this.type = 'showpopup';
			    },
			    hideConfirm() {
			        this.type = '';
			    },
			    async getLocation() {
			        // #ifdef APP-PLUS
			        let status = await this.checkPermission();
			        if (status !== 1) {
			            return;
			        }
			        // #endif
			        // #ifdef MP-WEIXIN || MP-TOUTIAO || MP-QQ
			        let status = await this.getSetting();
			        if (status === 2) {
			            this.showConfirm();
			            return;
			        }
			        // #endif
			        this.doGetLocation();						
			    },
			    doGetLocation() {
			        uni.getLocation({
			            success: (res) => {
			                this.hasLocation = true;
			                //this.location = formatLocation(res.longitude, res.latitude);	
							//var lon = parseFloat(this.location.longitude[0])+parseFloat(this.location.longitude[1]/60)
							//var lat = parseFloat(this.location.latitude[0])+parseFloat(this.location.latitude[1]/60)
							_self.tabIndex_all = 0
							_self.tabIndex_near = 1																																									
							_self.lon = res.longitude
							_self.lat = res.latitude																																												
							_self.action = 'near'																																																																																															
							this.gethouseall()																																			
			            },
			            fail: (err) => {
			                // #ifdef MP-BAIDU
			                if (err.errCode === 202 || err.errCode === 10003) { // 202模拟器 10003真机 user deny
			                    this.showConfirm();
			                }
			                // #endif
			                // #ifndef MP-BAIDU
			                if (err.errMsg.indexOf("auth deny") >= 0) {
			                    uni.showToast({
			                        title: "访问位置被拒绝"
			                    })
			                } else {
			                    uni.showToast({
			                        title: err.errMsg
									//title: "请检查手机定位服务是否开启"
			                    })
			                }
			                // #endif
			            }
			        })
			    },
			    getSetting: function() {
			        return new Promise((resolve, reject) => {
			            uni.getSetting({
			                success: (res) => {
			                    if (res.authSetting['scope.userLocation'] === undefined) {
			                        resolve(0);
			                        return;
			                    }
			                    if (res.authSetting['scope.userLocation']) {
			                        resolve(1);
			                    } else {
			                        resolve(2);
			                    }
			                }
			            });
			        });
			    },
			    openSetting: function() {
			        this.hideConfirm();
			        uni.openSetting({
			            success: (res) => {
			                if (res.authSetting && res.authSetting['scope.userLocation']) {
			                    this.doGetLocation();
			                }
			            },
			            fail: (err) => {}
			        })
			    },
			    async checkPermission() {
			        let status = permision.isIOS ? await permision.requestIOS('location') :
			            await permision.requestAndroid('android.permission.ACCESS_FINE_LOCATION');
			
			        if (status === null || status === 1) {
			            status = 1;
			        } else if (status === 2) {
			            uni.showModal({
			                content: "系统定位已关闭",
			                confirmText: "确定",
			                showCancel: false,
			                success: function(res) {
			                }
			            })
			        } else if (status.code) {
			            uni.showModal({
			                content: status.message							
			            })
			        } else {
			            uni.showModal({
			                content: "需要定位权限",
			                confirmText: "设置",
			                success: function(res) {
			                    if (res.confirm) {
			                        permision.gotoAppSetting();
			                    }
			                }
			            })
			        }			
			        return status;
			    },
			    clear: function() {
			        this.hasLocation = false
			    },
			getbanner(){
				uni.request({
					url: this.websiteUrl+'/userapi.php/Index/banner',
					method: 'GET',
					header: {
						'content-type':'application/x-www-form-urlencoded'				
					},
					data: {},
					success:function (res) {
						if(res.data.code == 1){
							_self.banner = res.data.data;
						}												
					}						
				})				
			},											
			gethouseall(){
				page = 1;
				_self.status = 'more'
				uni.showNavigationBarLoading();	
				uni.request({
					url: this.websiteUrl+'/userapi.php/Index/houseAll?page=1',
					method: 'POST',
					data:{
						action:_self.action,
						lon:_self.lon,
						lat:_self.lat,						
					},
					header: {
						'content-type':'application/x-www-form-urlencoded'				
					},
					success:function(res){
						page++
						_self.houseall = res.data.data.data
						uni.hideNavigationBarLoading();
						uni.stopPullDownRefresh();//得到数据后停止下拉刷新
					}
				});
			},
			getmorenews: function() {
				if(_self.status !== 'more'){
					return false
				}						    
				_self.status = 'loading'
			    uni.showNavigationBarLoading();//显示加载动画
			    uni.request({
			        url:this.websiteUrl+'/userapi.php/Index/houseAll?page='+page,
			        method: 'POST',
					header: {
						'content-type':'application/x-www-form-urlencoded'				
					},
					data: {
						action:_self.action,
						lon:_self.lon,
						lat:_self.lat,
					},					
			        success: function(res) {			           																		
			            if (res.data.data.data.length == 0) {//没有数据			                
							_self.status = 'noMore'					
			                uni.hideNavigationBarLoading();//关闭加载动画							
			                return false;
			            }
			            page++;//每触底一次 page +1										
			            _self.houseall = _self.houseall.concat(res.data.data.data);//将数据拼接在一起			            
						_self.status = 'more'					
			            uni.hideNavigationBarLoading();//关闭加载动画
			        }
			    });
			},				
			
			search(){				
				uni.navigateTo({
					url:"../trend/hsearch"
				})
			},
			all(){
				//_self.all = true
				//_self.near = false
				_self.tabIndex_all = 1,
				_self.tabIndex_near = 0
				_self.action = 'all'
				this.gethouseall()
			},			
		}
	}
</script>

<style>
	
	.border-bottom{
		border-bottom:2px #007AFF solid;
		
	}
    .discover {
		display: flex;
		flex-direction: column;
		align-items: center;
		background: #FFFFFF;
		height: 100%;
		
	}
	
	.discover .content{
		margin-top:88rpx;
		width:686rpx;
		
		height:100%;
	}
	
	.discover .site{
		width:100%;
		height: 88rpx;
	}
	
	.site .icon{
		width: 36rpx;
		height: 36rpx;
		margin-top:26rpx;
		float:left;
	}
	
	.site .note{
		width:auto;
		height: 88rpx;
		font-size:36rpx;
		line-height: 88rpx;
		color:#373737;
		float:left;
		margin-left:16rpx;
	}
	
	.site .arrow{
		width:12rpx;
		height:22rpx;
		margin-top:32rpx;
		margin-left:24rpx;
	}
	.search-nav{
		width:100%;
		height: 72rpx;
		position: relative;
	}
	
	.search{
		padding-left:72rpx;
		width:602rpx;
		height: 72rpx;
		background: #F8F8F8;
		border-radius: 16rpx;
		position:relative;
	}
	
	.search-icon{
		width:28rpx;
		height: 28rpx;
		position:absolute;
		left:32rpx;
		top:22rpx;
	}
	
	.hot{
		width:100%;
		height: 34rpx;
		margin-top:12rpx;
		font-size:24rpx;
		color:#999999;
	}
	
	.hot .icon{
		width:28rpx;
		height: 28rpx;
		float:left;
	}
	
	.hot .note{
		float:left;
		margin-left:8rpx;
	}
	
	ul{
		list-style-type:none;
	}
	
	.hot .keywords{
		
	}
	
	.hot .keywords li{
		float:left;
		margin-left:15rpx;
	}
	.swiper{
		width:98%;
		height:260rpx;
		margin-top:32rpx;
		border-radius:16rpx;
	}
	
	.swiper .swiper-item image{
		width:100%;
		height:260rpx;
	}
	.find-nav{
		width:100rpx;
		height:156rpx;
		margin-top:48rpx;
		float:left;
		
	}
	
	.find-nav image{
		width:120rpx;
		height: 120rpx;
	}
	
	.find-nav .note{
		width: 120rpx;
		line-height: 36rpx;
		font-size:24rpx;
		color:#373737;
		text-align:center;
	}
	.comm{
		float:left;
	}
	.rec{
		width:100%;
		height: 50rpx;
		margin-top:250rpx;
	}
	
	.rec .one{
		width:auto;
		height: auto;
		line-height: 50rpx;
		font-size:36rpx;
		color:#373737;
	}
	
	.rec .two{
		width:80rpx;
		width:80rpx;
		height: 100%;
		margin-left:350rpx;
	}
	
	.rec .two .note{
		width:80rpx;
		height: 28rpx;
		line-height: 50rpx;
		font-size:30rpx;
		color:#373737;
	}
	
	.rec .two image{
		width:40rpx;
		height:8rpx;
		margin-left:15rpx;
		
	}
	
	.rec .three{
		width:80rpx;
		width:80rpx;
		height: 100%;
		margin-left:30rpx;
	}
	.rec .three .note{
		width:80rpx;
		height: 28rpx;
		line-height: 50rpx;
		font-size:30rpx;
		color:#373737;
	}
	
	.rec .three image{
		width:40rpx;
		height:8rpx;
		margin-left:15rpx		
	}
	
	.con-top{
		width:100%;
		height: auto;
	}
	
	.con-bottom{
		width:100%;
		height: auto;
		background: #E5E5E5;
		display: flex;
		margin-top:48rpx;
		
	}
	
	
	.con-bottom .house{
		
		
		width:96%;
		margin-left:2%;
		height:auto;
	}
	.con-bottom .house-list{
		width:320rpx;
		height: 418rpx;
		float:left;
		background: white;
		border-radius: 8px 8px 0px 0px;
		margin-left:26rpx;
		margin-top:20rpx;
	}
	
	.con-bottom .house-list image{
		width:100%;
		height: 220rpx;
		border-radius: 8px 8px 0px 0px;
	}
	
	.con-bottom .house-list .title{
		width:auto;
		height: auto;
		font-size:28rpx;
		color:#373737;
		margin-top:24rpx;
		margin-left:16rpx;
	}

	.con-bottom .house-list .site{
		width:100%;
		height:34rpx;
		margin-top:12rpx;
		margin-left:16rpx;
	}
	
	.con-bottom .house-list .site image{
		width:28rpx;
		height: 28rpx;
		float:left;
	}
	
	.con-bottom .house-list .site .note{
		width:200rpx;
		height:34rpx;
		line-height: 34rpx;
		font-size:24rpx;
		color:#999999;
		float:left;
	}

	.con-bottom .price{
		font-size:32rpx;
		color:#FF635C;
		margin-top:24rpx;
		margin-left:16rpx;
	}
	
	
	
	
	
	
	
</style>
